<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 16/4/14
 * Time: 下午7:17
 * Describe:
 */

namespace console\controllers;

use console\models\BestryToDTry;
use console\models\DTryToBestry;
use console\models\LiketryToDTry;
use console\models\SyncOrderStatus;
use services\models\OrderGoods;
use \services\models\OrderInfo;
use \Yii;
# use common\models\tmall1\OrderGoods as TOrderGoods;
use common\helper\ArrayHelper;
use yii\console\Exception;

class OrderController extends \yii\console\Controller
{


    protected $log_type = 'order';

    public function init()
    {
        set_time_limit(3000);
        ini_set('memory_limit', '4G');
        parent::init();
    }

    /**
     *liketry order export into d_try order, run it one times only.
     */
    public function actionFromLiketry($begin_id = 0, $end_id = 0)
    {
        $itd = new LiketryToDTry();
        if ($begin_id) $itd->begin_id = (int)$begin_id;
        if ($end_id) $itd->end_id = (int)$end_id;
        $itd->run();
    }


    /**
     * origin bestry order export into d_try order, run it one times only.
     */
    public function actionFromBestry($begin_id = 0, $end_id = 0)
    {
        $btd = new BestryToDTry();
        if ($begin_id) $btd->begin_id = (int)$begin_id;
        if ($end_id) $btd->end_id = (int)$end_id;
        $btd->run();
    }


    /**
     * before 3 months order data export into d_order_history database;
     *
     * @throws \yii\db\Exception
     */
    public function actionToHistory()
    {
        Yii::info('3月前数据导出', static::className());
        $db          = Yii::$app->getDb();
        $transaction = $db->beginTransaction();
        try {
            Yii::info('3月前数据导出 订单', $this->log_type);
            $db->createCommand("INSERT INTO d_order_history.order_info
              SELECT *
              FROM d_try.order_info
              WHERE create_time < date_sub(curdate(), INTERVAL 3 MONTH);")
               ->execute();
            $db->createCommand("DELETE FROM d_try.order_info
                WHERE create_time < date_sub(curdate(), INTERVAL 3 MONTH);
                ")
               ->execute();
            Yii::info('3月前数据导出 订单商品', $this->log_type);
            $db->createCommand("INSERT INTO d_order_history.order_goods
                  SELECT *
                  FROM d_try.order_goods
                  WHERE create_time < date_sub(curdate(), INTERVAL 3 MONTH);")
               ->execute();
            $db->createCommand("DELETE FROM d_try.order_goods
                WHERE create_time < date_sub(curdate(), INTERVAL 3 MONTH);
                ")
               ->execute();
            Yii::info('3月前数据导出 订单物流数据', $this->log_type);
            $db->createCommand("INSERT INTO d_order_history.order_express
                  SELECT *
                  FROM d_try.order_express
                  WHERE create_time < date_sub(curdate(), INTERVAL 3 MONTH);")
               ->execute();
            $db->createCommand("DELETE FROM d_try.order_express
                WHERE create_time < date_sub(curdate(), INTERVAL 3 MONTH);
                ")
               ->execute();
            $transaction->commit();
            Yii::info('3月前数据导出成功', $this->log_type);
        } catch (Exception $e) {
            $transaction->rollBack();
            Yii::info('3月前数据导出失败', $this->log_type);
        }
    }

    /**
     * d_try order data export into tmall1 order table
     */
    public function actionToBestry()
    {
        $dtb = new DTryToBestry();
        $dtb->run();
    }

    /**
     * synchronization log, synchronization order status.
     */
    public function actionSyncOrderStatus()
    {
        $sos = new SyncOrderStatus();
        $sos->run();
    }



    /**
     * cancle order before 12 hours and unpay.
     */
    public function actionCancelOrders()
    {
        $order = new \services\models\Order();
        #$alipay = new \leyestd\alipay\AlipayCloseOrder();
        $orders = OrderInfo::find()->where(['status' => OrderInfo::$STATUS_ORDER_CREATED ])
                           ->andFilterWhere(['<>', 'pay_status', OrderInfo::$PAY_STATUS_SUCCESS])
                           ->andFilterWhere(['<=', 'create_time', date('Y-m-d H:i:s', strtotime('-12hour'))])
                           ->andFilterWhere(['>', 'create_time', date('Y-m-d H:i:s', strtotime('-36hour'))])
                           ->select(['order_sn', 'order_info_id'])
                           ->all();
        foreach ($orders as $item) {
            $order->order_info_id = $item->order_info_id;
            try{

                $order->cancelOrder();
                if (!$order->hasErrors()) {
                    #$alipay->closeOrder($item->order_sn);
                    Yii::info("cancel order :{$item->order_info_id} order_sn:{$item->order_sn}", 'order');

                } else {
                    Yii::info("cancel order fail:{$item->order_info_id} order_sn:{$item->order_sn} ".ArrayHelper::arrayToString($order->getErrors()), 'order');
                }
            }catch(\yii\base\Exception $e){
                Yii::info("cancel order :{$item->order_info_id} order_sn:{$item->order_sn} ".$e->getMessage(), 'order');
            }
        }

    }


    /*public function actionGoodsAbc()
    {

        $result = OrderGoods::find()->where('order_info_id between 40000000 and 50393958')
                            ->all();
        /** @var TOrderGoods $tog */
    /** @var OrderGoods $od
    foreach ($result as $od) {
     * echo $od->order_goods_id, "\n";
     * #echo $od->order_goods_id, "\n";
     * try {
     * $tog                = new TOrderGoods();
     * $tog->order_id      = $od->order_info_id;
     * $tog->goods_id      = $od->goods_id;
     * $tog->product_id    = $od->product_id;
     * $tog->member_uid    = $od->bestry_uid;
     * $tog->buy_number    = $od->buy_number;
     * $tog->buy_price     = $od->buy_price;
     * $tog->addtime       = strtotime($od->create_time);
     * $tog->free_order_id = $od->free_gift;
     * $tog->comment_id    = $od->commented;
     * $tog->act_id        = $od->activity_id;
     * $tog->price_type    = $od->price_type;
     * $tog->jfs           = $od->try_coin;
     * $tog->save();
     * if ($od->hasErrors()) {
     * static::info('导入 goods 失败ID:' . $od->order_goods_id . ArrayHelper::arrayToString($tog->getFirstErrors()));
     *
     * }
     * } catch (Exception $e) {
     *
     * static::info('导入order goods:' . $od->order_goods_id. $e->getMessage());
     * }
     *
     * }
     * }
     *
     * public static function info($msg)
     * {
     * Yii::info(getmypid() . ' ' . $msg, 'order');
     * }*/

}